<template>
  <div class="">
    <el-form ref="mergeJoin" :model="mergeJoin" label-width="280px">
      <el-form-item label="步骤名称" prop="name">
        <el-input v-model="mergeJoin.name"/>
      </el-form-item>
      <el-form-item label="第一个步骤" prop="step1">
        <el-select v-model="mergeJoin.step1" placeholder="请选择" style="width:100%" @focus="getStepsList">
          <el-option
            v-for="item in stepsList"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="第二个步骤" prop="step2">
        <el-select v-model="mergeJoin.step2" placeholder="请选择" style="width:100%" @focus="getStepsList">
          <el-option
            v-for="item in stepsList"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="连接类型" prop="join_type">
        <el-select v-model="mergeJoin.join_type" placeholder="请选择" style="width:100%">
          <el-option
            v-for="item in typeList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <span>第一个步骤的连接字段</span>
          <el-table :data="mergeJoin.keys_1" border style="margin-top:10px; width: 100%;" height="170">
            <el-table-column label="操作" align="center" fixed width="80" :resizable="false">
              <template slot-scope="scope">
                <div class="optionStyle">
                  <el-button
                    type="text"
                    @click="removeFirstStepFields(scope.$index)"
                  >
                    移除
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column property="name" label="连接字段">
              <!--<template slot-scope="scope">-->
              <!--<el-input v-model="scope.row.key" size="mini"></el-input>-->
              <!--</template>-->
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.name"
                  filterable
                  allow-create
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in fieldOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </template>
            </el-table-column>
          </el-table>
          <el-col :span="24">
            <el-row type="flex">
<!--              <el-button class="el-table-add-row" icon="el-icon-plus" @click="addFirstStepField()">-->
<!--                添加-->
<!--              </el-button>-->
              <div style="width: 20px;"/>
              <el-button class="el-table-add-row" icon="el-icon-thumb" @click="getFirstStepFields">
                获取连接字段
              </el-button>
            </el-row>
          </el-col>
        </el-col>
        <el-col :span="12">
          <span>第二个步骤的连接字段</span>
          <el-table :data="mergeJoin.keys_2" border style="margin-top:10px; width: 100%;" height="170">
            <el-table-column label="操作" align="center" fixed width="80" :resizable="false">
              <template slot-scope="scope">
                <div class="optionStyle">
                  <el-button
                    type="text"
                    @click="removeSecondStepFields(scope.$index)"
                  >
                    移除
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column property="name" label="连接字段">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.name"
                  filterable
                  allow-create
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in fieldOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </template>
            </el-table-column>
          </el-table>
          <el-col :span="24">
            <el-row type="flex">
<!--              <el-button class="el-table-add-row" icon="el-icon-plus" @click="addSecondStepField()">-->
<!--                添加-->
<!--              </el-button>-->
              <div style="width: 20px;"/>
              <el-button class="el-table-add-row" icon="el-icon-thumb" @click="getSecondStepFields">
                获取连接字段
              </el-button>
            </el-row>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
    <div class="el-dialog__footer">
      <span class="dialog-footer">
        <el-button
          icon="el-icon-back"
          @click="cancel"
        >取消
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-check"
          @click="handleSaveData()"
        >确定
        </el-button>
      </span>
    </div>
  </div>
</template>

<script>
/* eslint-disable new-cap */
import API from '../../../../../api/index'
import mxgraph from '../../../../../graph/VueMxGraphLoader'
import xmlToFlinkJSON from '../../../../../utils/xmlToFlinkJson'
import { flinkInputFields } from '../../../../../api/modules/trans'
import { flinkPrevioussteps } from '../../../../../api/modules/trans'
import { previoussteps } from '../../../../../api/modules/trans'
const {
  mxUtils,
  mxCodec
} = mxgraph
export default {
  name: 'MergeJoin',
  props: {
    name: String
  },
  data() {
    return {
      fieldOptions: [],
      mergeJoin: {
        type: 'MergeJoin',
        name: '',
        step1: [],
        step2: [],
        join_type: 'FULL OUTER',
        keys_1: [],
        keys_2: []
      },
      temp: {
        type: 'MergeJoin',
        name: '',
        step1: [],
        step2: [],
        join_type: 'FULL OUTER',
        keys_1: [],
        keys_2: []
      },
      graph: null,
      tempMergeRows: null,
      stepsList: [],
      typeList: [{ code: 'INNER', name: 'INNER' },
        { code: 'LEFT OUTER', name: 'LEFT OUTER' },
        { code: 'RIGHT OUTER', name: 'RIGHT OUTER' },
        { code: 'FULL OUTER', name: 'FULL OUTER' },
        { code: 'UNION', name: 'UNION' }
      ]
    }
  },
  methods: {
    // 回显数据
    loadData(data) {
      if (data) {
        this.$forceUpdate()
        this.mergeJoin = Object.assign({}, data)
        this.tempMergeRows = JSON.parse(JSON.stringify(data))
      }
    },
    setGraph(val) {
      this.graph = val
      this.getStepsList()
    },
    // 重置表单数据
    resetFormData(stepname) {
      this.$forceUpdate()
      this.$refs['mergeJoin'].resetFields()
      this.mergeJoin = JSON.parse(JSON.stringify(this.temp))
      this.mergeJoin.name = stepname
    },
    saveTempPluginData(formData) {
      this.$emit('saveTempPluginData', formData)
    },
    getXml() {
      // this.saveTempPluginData(this.mergeJoin)
      // const graph = this.graph
      // const enc = new mxCodec(mxUtils.createXmlDocument())
      // const node = enc.encode(graph.getModel())
      // const value = mxUtils.getPrettyXml(node)
      // return value
      this.saveTempPluginData(this.mergeJoin)
      const graph = this.graph
      const enc = new mxCodec(mxUtils.createXmlDocument())
      const node = enc.encode(graph.getModel())
      const queryParJson = xmlToFlinkJSON.xmlToFlinkModels(node)
      queryParJson.models.model['step_name'] = this.mergeJoin.name
      queryParJson.models.model['step_type'] = 'PREV'
      return queryParJson
    },
    getXml2() {
      this.saveTempPluginData(this.mergeJoin)
      const graph = this.graph
      const enc = new mxCodec(mxUtils.createXmlDocument())
      const node = enc.encode(graph.getModel())
      const value = mxUtils.getPrettyXml(node)
      return value
    },
    async addSecondStepField() {
      const obj = {}
      this.mergeJoin.keys_2.push(obj)
      this.$nextTick(() => {
        const container = this.$el.querySelector('#field > .el-table__body-wrapper')
        container.scrollTop = container.scrollHeight
      })
      if (this.fieldOptions.length === 0) {
        const value = await this.getXml()
        API.trans.flinkInputFields(value, { 'stepName': this.mergeJoin.step2 }).then(res => {
          if (res.data) {
            const tempFields = []
            const tempStreamField = Object.assign([], res.data.data.data.fields)
            tempStreamField.forEach(element => {
              const obj = {}
              obj['name'] = element.name
              obj['comments'] = element.comments
              tempFields.push(obj)
            })
            this.$set(this, 'fieldOptions', tempFields)
          } else {
            this.fieldOptions = []
          }
        })
      }
    },
    async addFirstStepField() {
      const obj = {
        key: ''
      }
      this.mergeJoin.keys_1.push(obj)
      this.$nextTick(() => {
        const container = this.$el.querySelector('#field > .el-table__body-wrapper')
        container.scrollTop = container.scrollHeight
      })
      if (this.fieldOptions.length === 0) {
        const value = await this.getXml()
        API.trans.flinkInputFields(value, { 'stepName': this.mergeJoin.step1 }).then(res => {
          if (res.data) {
            const tempFields = []
            const tempStreamField = Object.assign([], res.data.data.data.fields)
            tempStreamField.forEach(element => {
              const obj = {}
              obj['name'] = element.name
              obj['comments'] = element.comments
              tempFields.push(obj)
            })
            this.$set(this, 'fieldOptions', tempFields)
          } else {
            this.fieldOptions = []
          }
        })
      }
    },
    // 获取第一个步骤的连接字段
    async getFirstStepFields() {
      const value = await this.getXml()
      this.mergeJoin.keys_1 = []
      if (this.mergeJoin.step1) {
        API.trans.flinkInputFields(value, { 'stepName': this.mergeJoin.step1 }).then(res => {
          if (res.data) {
            for (var i = 0; i < res.data.data.data.fields.length; i++) {
              this.mergeJoin.keys_1.push({ name: res.data.data.data.fields[i].name })
            }
          } else {
            this.mergeJoin.keys_1 = []
          }
        })
      }
    },
    // 获取第二个步骤的连接字段
    async getSecondStepFields() {
      const value = await this.getXml()
      this.mergeJoin.keys_2 = []
      if (this.mergeJoin.step2) {
        API.trans.flinkInputFields(value, { 'stepName': this.mergeJoin.step2 }).then(res => {
          console.log('========')
          console.log(res.data.data.data.fields)
          if (res.data) {
            for (var i = 0; i < res.data.data.data.fields.length; i++) {
              this.mergeJoin.keys_2.push({ name: res.data.data.data.fields[i].name })
            }
          } else {
            this.mergeJoin.keys_2 = []
          }
          console.log(this.mergeJoin.keys_2)
        })
      }
    },
    // 移除第一个步骤的连接字段
    removeFirstStepFields(index) {
      this.mergeJoin.keys_1.splice(index, 1)
    },
    // 移除第二个步骤的连接字段
    removeSecondStepFields(index) {
      this.mergeJoin.keys_2.splice(index, 1)
    },
    // 获取第一、二个步骤的list
    async getStepsList() {
      if (this.stepsList.length === 0) {
        const value = await this.getXml()
        if (this.mergeJoin.name) {
          API.trans.flinkPrevioussteps(value, { 'stepName': this.mergeJoin.name }).then(res => {
            if (res.data) {
              this.stepsList = res.data.data.data
            } else {
              this.stepsList = []
            }
          })
        }
      }
    },
    // 保存表单数据
    handleSaveData() {
      if (this.mergeJoin.name) {
        this.$emit('savePluginData', this.mergeJoin)
      } else {
        this.$message({
          message: '步骤名称必填',
          type: 'warning'
        })
      }
    },
    // 重置数据
    cancel() {
      if (this.tempMergeRows) {
        this.saveTempPluginData(this.tempMergeRows)
      } else {
        const tempdata = JSON.parse(JSON.stringify(this.temp))
        tempdata['name'] = this.mergeJoin.name
        this.saveTempPluginData(tempdata)
      }
      this.$emit('cancel')
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.el-form-item {
  margin-bottom: 10px !important;
}
.el-tabs /deep/ .el-tabs__content {
  padding: 15px !important;
}
.el-dialog__footer {
  margin-top: 49px;
}
.optionStyle button {
  margin: 0px
}

</style>
